package com.wz.wzbubbleai.view;

/**
 * Created by wangbin on 18-1-10.
 */

import android.content.Context;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;

import com.wz.wzbubbleai.R;
import com.wz.wzbubbleai.apdater.ChatAdapter;
import com.wz.wzbubbleai.apdater.Item.BaseListItem;
import com.wz.wzbubbleai.apdater.Item.BubbleTextItem;
import com.wz.wzbubbleai.apdater.Item.UserTextItem;
import com.wz.wzbubbleai.database.ChatDataDao;
import com.wz.wzbubbleai.enity.ChatModel;
import com.wz.wzbubbleai.utils.LogUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 弹窗辅助类
 *
 * @ClassName MainView
 *
 *
 */
public class MainView implements View.OnClickListener{

    private static final String LOG_TAG = "MainView";
    private static View mView = null;
    private static WindowManager mWindowManager = null;
    private static Context mContext = null;

    public static Boolean isShown = false;

    ChatDataDao mDao = null;

    /**
     * 显示弹出框
     *
     * @param context
     */
    public void showPopupWindow(final Context context) {
        if (isShown) {
            LogUtil.i(LOG_TAG, "return cause already shown");
            return;
        }

        isShown = true;
        LogUtil.i(LOG_TAG, "showPopupWindow");

        // 获取应用的Context
        mContext = context.getApplicationContext();
        // 获取WindowManager
        mWindowManager = (WindowManager) mContext
                .getSystemService(Context.WINDOW_SERVICE);

        mView = setUpView(context);

        final WindowManager.LayoutParams params = new WindowManager.LayoutParams();

        // 类型
        params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        //params.type = WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW;

        // 设置flag
        int flags = WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
        // | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        // 如果设置了WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE，弹出的View收不到Back键的事件
        params.flags = flags;
        // 不设置这个弹出框的透明遮罩显示为黑色
        params.format = PixelFormat.TRANSLUCENT;
        // FLAG_NOT_TOUCH_MODAL不阻塞事件传递到后面的窗口
        // 设置 FLAG_NOT_FOCUSABLE 悬浮窗口较小时，后面的应用图标由不可长按变为可长按
        // 不设置这个flag的话，home页的划屏会有问题

        params.width = LayoutParams.MATCH_PARENT;
        params.height = LayoutParams.MATCH_PARENT;

        params.gravity = Gravity.CENTER;

        mWindowManager.addView(mView, params);

        LogUtil.i(LOG_TAG, "add view");
    }


    private static void hideSystemUI() {
        int flag =mView.getWindowSystemUiVisibility();

        int fullScreen = 0x8;
        if (flag == fullScreen) {
            if ((flag & fullScreen) != 0) {
                mView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
            }
        }else {
            if ((flag & fullScreen) == 0) {
                mView.setSystemUiVisibility(flag | fullScreen);
            }
        }
    }

    public static boolean isWindowShowing(){
        return isShown;
    }

    /**
     * 隐藏弹出框
     */
    public static void hidePopupWindow() {
        LogUtil.i(LOG_TAG, "hide " + isShown + ", " + mView);
        if (isShown && null != mView) {
            LogUtil.i(LOG_TAG, "hidePopupWindow");
            mWindowManager.removeView(mView);
            isShown = false;
        }

    }

    private View setUpView(final Context context) {

        LogUtil.i(LOG_TAG, "setUp view");

        View view = LayoutInflater.from(context).inflate(R.layout.main_view,
                null);

        mView = view;
        mDao = new ChatDataDao(context);
        initChatView(view,context);
        hideSystemUI();
        initClickEvent(view);
        return view;
    }


    private List<BaseListItem> initChatData(){
        /*List<BaseListItem> chatList = new ArrayList<BaseListItem>();
        //
        BubbleTextItem textItem = new BubbleTextItem(BaseListItem.TYPE_BUBBLE_TEXT,"","测试回顾一下单一类型的listview,其" +
                "ViewHolder的工作机制在于系统会将滑出屏幕的item的view回收起来,并作为getView的第二个参数 convertView 传入");

        chatList.add(textItem);

        UserTextItem userItem = new UserTextItem(BaseListItem.TYPE_USER_TEXT,"","应用程序中起着");
        //"应用程序中起着非常重要的作用，应用也非常广泛，" +"它可看作是数据源和UI组件之间的桥梁"
        chatList.add(userItem);
        BubbleTextItem textItem2 = new BubbleTextItem(BaseListItem.TYPE_BUBBLE_TEXT,"","我要看电视");
        chatList.add(textItem2);

        UserTextItem userItem2 = new UserTextItem(BaseListItem.TYPE_USER_TEXT,"","好的,请稍等,正在为您切换");
        //"应用程序中起着非常重要的作用，应用也非常广泛，" +"它可看作是数据源和UI组件之间的桥梁"
        chatList.add(userItem2);*/
        //mDao.deleteDate("");
        mDao.addDate(new ChatModel(1,"测试回顾一下单一类型的listview,其" +
                "ViewHolder的工作机制在于系统会将滑出屏幕的item的view回收起来," +
                "并作为getView的第二个参数 convertView 传入","",0,""));
        mDao.addDate(new ChatModel(0,"我要看电视","",0,""));
        mDao.addDate(new ChatModel(1,"测试回顾一下单一类型的listview,其" +
                "ViewHolder的工作机制在于系统会将滑出屏幕的item的view回收起来," +
                "并作为getView的第二个参数 convertView 传入","",0,""));
        mDao.addDate(new ChatModel(0,"我要看电视2222","",0,""));

        List<BaseListItem> chatList = mDao.getChatDate("");
        return chatList;
    }

    /**
     * 初始化listview
     * @param view
     * @param mContext
     */
    private void initChatView(View view,Context mContext){
        ChatView chatView = view.findViewById(R.id.chat_view);
        ChatAdapter chatAdapter = new ChatAdapter(mContext);
        chatView.setAdapter(chatAdapter);
        List<BaseListItem> listItems = initChatData();
        chatAdapter.setList(listItems);
        chatAdapter.notifyDataSetChanged();
    }

    /**
     * 初始化点击事件
     * @param view
     */
    public void initClickEvent(View view){
        ImageButton closBtn = (ImageButton) view.findViewById(R.id.close_bt);

        closBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LogUtil.i(LOG_TAG, "cancel on click");
                MainView.hidePopupWindow();
            }
        });

        // 点击窗口外部区域可消除
        // 将悬浮窗设置为全屏大小，外层有个透明背景，中间一部分视为内容区域
        final View popupWindowView = view.findViewById(R.id.main_ll);// 非透明的内容区域

        view.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                LogUtil.i(LOG_TAG, "onTouch");
                int x = (int) event.getX();
                int y = (int) event.getY();
                Rect rect = new Rect();
                popupWindowView.getGlobalVisibleRect(rect);
                if (!rect.contains(x, y)) {
                    MainView.hidePopupWindow();
                }

                LogUtil.i(LOG_TAG, "onTouch : " + x + ", " + y + ", rect: "
                        + rect);
                return false;
            }
        });

        // 点击back键可消除
        view.setOnKeyListener(new View.OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                switch (keyCode) {
                    case KeyEvent.KEYCODE_BACK:
                        MainView.hidePopupWindow();
                        return true;
                    default:
                        return false;
                }
            }
        });

        Button alwaysVoice = view.findViewById(R.id.voice_normal_bt);
        Button helpButton = view.findViewById(R.id.help_alert_bt);

        alwaysVoice.setOnClickListener(this);
        helpButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.voice_normal_bt:
                showAlwaysView();
                break;
        }
    }

    /**
     *展示常用语音
     */
    public void showAlwaysView(){
        if(mView != null){
            LogUtil.d("showAlwaysView");
            LinearLayout showLayout = mView.findViewById(R.id.show_ll);
            View alwaysView = LayoutInflater.from(mContext).inflate(R.layout.layout,
                    null);
            showLayout.addView(alwaysView);
        }
    }
}